import { useReducer } from 'react';
import TaskAdd from './TaskAdd';
import TaskList from './TaskList';

// 定义任务类型
interface Task {
	id: number;
	text: string;
	done: boolean;
}

// 定义 Action 类型
type TasksAction =
	| { type: 'added'; id: number; text: string }
	| { type: 'changed'; task: Task }
	| { type: 'deleted'; id: number };

// 定义初始状态类型
type TasksState = Task[];

// 定义 dispatch 类型
const TASK_ACTIONS = {
	ADD: 'added',
	CHANGE: 'changed',
	DELETE: 'deleted'
} as const;

export default function TaskApp() {
	const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);

	function handleAddTask(text: string) {
		dispatch({
			type: TASK_ACTIONS.ADD,
			id: nextId++,
			text
		});
	}

	function handleChangeTask(task: Task) {
		dispatch({
			type: TASK_ACTIONS.CHANGE,
			task
		});
	}

	function handleDeleteTask(taskId: number) {
		dispatch({
			type: TASK_ACTIONS.DELETE,
			id: taskId
		});
	}

	return (
		<>
			<h1>Day off in Kyoto</h1>
			<TaskAdd onAddTask={handleAddTask} />
			<TaskList tasks={tasks} onChangeTask={handleChangeTask} onDeleteTask={handleDeleteTask} />
		</>
	);
}

function tasksReducer(state: TasksState, action: TasksAction): TasksState {
	switch (action.type) {
		case TASK_ACTIONS.ADD:
			return [
				...state,
				{
					id: action.id,
					text: action.text,
					done: false
				}
			];
		case TASK_ACTIONS.CHANGE:
			return state.map(t => (t.id === action.task.id ? action.task : t));
		case TASK_ACTIONS.DELETE:
			return state.filter(t => t.id !== action.id);
		default:
			throw Error('Unknown action: ' + (action satisfies never));
	}
}

let nextId = 3;
const initialTasks: TasksState = [
	{ id: 0, text: 'Philosopher’s Path', done: true },
	{ id: 1, text: 'Visit the temple', done: false },
	{ id: 2, text: 'Drink matcha', done: false }
];
